package com.example.farmeri.data;


import com.example.farmeri.data.config.ServiceConfig;
import com.example.farmeri.http.ComInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private static volatile RetrofitManager manager;

    public static synchronized RetrofitManager getManager() {
        if (manager == null) {
            manager = new RetrofitManager();
        }
        return manager;
    }

    private Retrofit retrofit;

    public Retrofit getRetrofit() {
        if (retrofit == null) {
            create();
        }
        return retrofit;
    }

    private void create() {
        ComInterceptor interceptor = new ComInterceptor();
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        okBuilder.addInterceptor(interceptor);
        okBuilder.connectTimeout(1, TimeUnit.MINUTES);
        okBuilder.readTimeout(1, TimeUnit.MINUTES);
        okBuilder.writeTimeout(1, TimeUnit.MINUTES);

        Gson gson = new GsonBuilder()
                // 服务器返回的Date格式是毫秒级   需要使用适配器
                .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong()))
                .create();

        Retrofit.Builder builder = new Retrofit.Builder();
        //请求链接前缀，所有接口不变到部分，者字符串必须以/结尾
        builder.baseUrl(ServiceConfig.url);
        //用于做网络请求到客户端（okHttp3）
        builder.client(okBuilder.build());
        //解析工程，可以帮我们把数据直接解析成对象
        builder.addConverterFactory(GsonConverterFactory.create(gson));
        //异步回调适配工程
        builder.addCallAdapterFactory(RxJava3CallAdapterFactory.create());

        retrofit = builder.build();
    }
}